<template>
  <el-cascader
    v-model="groupPath"
    :options="tree"
    style="width: 100%"
    :show-all-levels="false"
    :props="{ value: 'path', label: 'name', emitPath: false , checkStrictly: true}"
    @change="groupChange"
    :clearable="clearable"
  ></el-cascader>
</template>

<script>
import { groupTree , tenantTree } from '@/api/user';
export default {
  name: 'SelectGroup',
  props: {
    /* 部门ID */
    value: {
      type: [String, Number],
      default: null
    },
    groupNum: {
      type: [Number],
      default: 0
    },
    clearable: {
        type: Boolean,
        default: false
    },
    api: {
        type: [String, null],
        default: null
    }
  },
  data() {
    return {
      tree: [],
      groupPath: null
    };
  },
  watch: {
    value: {
      handler(val) {
        this.groupPath = val || null;
      },
      immediate: true
    }
  },
  created() {
    this.getGroupTree();
  },
  methods: {
    tenantTree,
    // 获取部门树
    async getGroupTree() {
        if(this.api) {
           const res = await this[this.api]();
           this.tree = res.data || [];
        }else{
            groupTree().then((res) => {
              if(this.groupNum == 3) {
                this.tree = this.getTreeChild(res.data)
              }else{
                this.tree = res.data || [];
              }
            });
        }
    },
    getTreeChild(childrenMap) {
      var children = JSON.parse(JSON.stringify(childrenMap))
      children.forEach((el, index) => {
        if (el.children && el.children.length) {
            el.children.forEach(c => {
              if (c.children && c.children.length) {
                c.children.forEach(u => {
                  u.children = null;
                })
                return
              }
            })
            return
        }
      })
      return children
    },
    groupChange(e) {
      this.selectGroupItem = null;
      this.getGroupItem(this.tree, e);
      this.$emit('input', e);
      this.$emit('change', this.selectGroupItem);
    },
    getGroupItem(tree, path) {
      if (!tree || !tree.length) return null;
      if (!path) return null;
      if (this.selectGroupItem) return null;
      const item = tree.find((i) => i.path == path);
      console.log('查找结果：', item);
      if (item) {
        this.selectGroupItem = item;
      } else {
        tree.map((item) => {
          this.getGroupItem(item.children, path);
        });
      }
    }
  }
};
</script>

<style scoped lang="scss"></style>
